{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "dataSet = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])\n",
    "labels = ['A', 'A', 'B', 'B']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "dataSetSize = dataSet.shape[0]\n",
    "print(dataSetSize)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[-1.  -1.1]\n",
      " [-1.  -1. ]\n",
      " [ 0.   0. ]\n",
      " [ 0.  -0.1]]\n"
     ]
    }
   ],
   "source": [
    "inX = [0, 0]\n",
    "k = 3\n",
    "diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet\n",
    "print(diffMat)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.48660687 1.41421356 0.         0.1       ]\n",
      "[2 3 1 0]\n"
     ]
    }
   ],
   "source": [
    "sqDiffMat = diffMat**2\n",
    "sqDistances = sqDiffMat.sum(axis=1)\n",
    "distances = sqDistances**0.5\n",
    "sortedDistIndicies = distances.argsort()  \n",
    "print(distances)\n",
    "print(sortedDistIndicies)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'B': 2, 'A': 1}\n",
      "[('B', 2), ('A', 1)]\n"
     ]
    }
   ],
   "source": [
    "classCount = {}\n",
    "for i in range(k):\n",
    "    voteIlabel = labels[sortedDistIndicies[i]]\n",
    "    classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1\n",
    "print(classCount)\n",
    "sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)\n",
    "print(sortedClassCount)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
